/**
 * @projectName study-note
 * @package thread
 * @className thread.Thread01
 */
package thread;

import java.util.concurrent.*;

/**
 * Thread01
 * @description 线程创建方式
 * 1、继承Thread类，实现run方法
 * 2、实现Runnbale接口，实现run方法
 * 3、实现Callable接口，实现call方法，可以return
 * 4、线程池启动
 * @author answer_wx
 * @date 2022/7/6 10:32
 * @version 1.0
 */
public class Thread01 {
    public static class MyThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(50); // 线程沉睡
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Mythread " + i);
            }
        }
    }

    public static class MyRunnable implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                Thread.yield(); // 进入等待队列，返回就绪状态
                System.out.println("MyRunnable " + i);
            }
        }
    }

    public static class MyCallable implements Callable<String> {
        @Override
        public String call() {
            for (int i = 0; i < 10; i++) {
                System.out.println("MyCallable " + i);
            }
            return "可以提供线程返回值";
        }
    }

    public static void main(String[] args) {
        Thread myThread = new MyThread();
        myThread.start();

        Runnable myRunnable = new MyRunnable();
        new Thread(myRunnable).start();

        Callable<String> myCallable = new MyCallable();
        FutureTask<String> futureTask = new FutureTask<>(myCallable);
        new Thread(futureTask).start();
        try {
            System.out.println(futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5,
                10,
                1,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(50));
        /**
         * 执行线程没有返回值
         */
        threadPoolExecutor.execute(myThread);
        /**
         * 提交线程，可以得到返回值
         */
        try {
            Future<?> submit = threadPoolExecutor.submit(myCallable);
            System.out.println(submit.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        threadPoolExecutor.shutdown();
    }
}